//
//  JXReviewsController.m
//  JiaoX
//
//  Created by yinqy on 15/1/6.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXReviewsController.h"
#import "HomeDataTool.h"
#import "ReviewsResult.h"
#import "ReviewsHeaderView.h"
#import "JXReplyCommentView.h"
#import "CommentCell.h"
#import "EmptyComtView.h"
#import "CommentUtils.h"
#import "MJRefresh.h"
#import "CustomActionSheet.h"
#import "DESSecurity.h"
#import "StringWithHtmlUtil.h"
#import "UIImageView+WebCache.h"
#import "JXComtDetailCtl.h"

//回复地址
#define REPLY_URL @"reviews/recomment"

@interface JXReviewsController ()<ReviewsHeaderViewDelegate,UITableViewDelegate,UITableViewDataSource,JXReplyCommentViewDelegate,CommentCellViewDelegate,CustomActionSheetDelegate>
{
    ReviewsHeaderView *_headerView;
    UITableView *_tableView;
    JXReplyCommentView *_replyView;
    NSMutableArray *_commentFrameArray;
    
    //回复需要用到的东西
    NSString *_commentId;
    NSString *_userIdOther;
    NSString *_userNameOther;
    NSString *_commentType;//回复的类型：0代表回复的是帖子，1代表回复的是主评论，2代表回复的是子评论
    
    //回复主评论的位置
    NSInteger _replySection;
    //回复子评论的位置
    NSInteger _replyIndex;
    
    ReviewsResult *_reviewsResult;
    
    //弹出窗体背后的button
    UIButton *_bg_btn;
    CustomActionSheet* sheet;
}

@property (nonatomic,copy)NSString *reviewsId;
@property (nonatomic,copy)NSString *reviewsTitle;
@property (nonatomic,copy)NSString *shareImgUrl;
@property (nonatomic,strong)UIImageView *shareImg;
@end

@implementation JXReviewsController

+(instancetype)initWithReviewId:(NSString *)reviewsId title:(NSString *)title reviewsTitle:(NSString *)reviewsTitle shareImgUrl:(NSString*)shareImgUrl{
    JXReviewsController *result = [[JXReviewsController alloc]init];
    result.reviewsId = reviewsId;
    result.title = title;
    result.reviewsTitle = reviewsTitle;
    result.shareImgUrl = shareImgUrl;
    return result;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.RightBarButtonItem = [UIBarButtonItem itemWithImageName:@"btn_title_share_nor" highImageName:@"btn_title_share_pre" target:self action:@selector(share)];
    
    //遮盖
    _bg_btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, JXScreenW, JXScreenH)];
    [_bg_btn setBackgroundColor:[UIColor clearColor]];
    [_bg_btn addTarget:self action:@selector(beforeClick) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow addSubview:_bg_btn];
    [_bg_btn setHidden:YES];
    
    _replySection = _replyIndex = -1;
    
    _commentFrameArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    [_tableView setHeight:_tableView.height-REPLY_VIEW_HEIGHT];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorColor:JXColor(242, 242, 242)];
    [self.view addSubview:_tableView];
    
    _replyView = [[JXReplyCommentView alloc]initWithPlaceholder:@"闲话这货"];
    _replyView.x = 0;
    _replyView.y = self.view.height-REPLY_VIEW_HEIGHT;
    _replyView.delegate = self;
    [self.view addSubview:_replyView];
    
    ReviewsHeaderView *headerView = [[ReviewsHeaderView alloc]init];
    headerView.reviewsId = self.reviewsId;
    [headerView setTitle:self.reviewsTitle];
    [_tableView setTableHeaderView:headerView];
    _headerView = headerView;
    _headerView.delegate = self;
    [self requestDataWithId:self.reviewsId lastComtId:@""];
    
    [_tableView addFooterWithTarget:self action:@selector(footerRefresh)];
}
-(void)footerRefresh{
    CommentViewFrame *fream = [_commentFrameArray lastObject];
    NSString *lastId = fream.comtInfo.commentId;
    [self requestDataWithId:self.reviewsId lastComtId:[Utils isBlankString:lastId]?@"":lastId];
}

-(void)viewDidLayoutSubviews
{
    [Utils setSeparatorInsetWithTableView:_tableView insets:UIEdgeInsetsMake(0, JXPublicInset, 0, 0)];
}

-(void)requestDataWithId:(NSString *)reviewsId lastComtId:(NSString *)lastComtId{
    [HomeDataTool reviewsDataWithId:reviewsId lastComtId:lastComtId success:^(ReviewsResult *result) {
        if([Utils isBlankString:result.data]){
            if (![_headerView haveData]) {
                //加载成功
                _reviewsResult = result;
                [_headerView setReviewsData:result.reviews prodList:result.productList];
            }
            [self comtFramesWithData:result];
        }else{
            //弹出失败的提示
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
        [Utils refreshComplete:_tableView];
    } failure:^(NSError *error) {
        //加载失败
        [Utils refreshComplete:_tableView];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}

-(void)comtFramesWithData:(ReviewsResult *)result{
    if(!result.allComment.count)
    {
        [self showFooterView:NO];
        return;
    }
    [_commentFrameArray removeAllObjects];
    for (int i=0; i<result.allComment.count; i++) {
        CommentViewFrame *frame = [[CommentViewFrame alloc]init];
        CommentInfo *comtInfo = result.allComment[i];
        //传递专题数据，计算所有子控件的frame
        frame.comtInfo = comtInfo;
        [_commentFrameArray addObject:frame];
    }
    [_tableView reloadData];
}

- (void)webviewLoadFinish{
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
}
#pragma Mark - 论坛评论相关 delegte

-(void)bottomViewReplyBtnClick:(NSString *)replyContent{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    [CommentUtils replyCommentWithController:self replyUrl:REPLY_URL ReplyType:REPLY_TYPE_REVIEWSID replyMainId:_reviewsId commentId:_commentId replyContent:replyContent userIdOther:_userIdOther commentType:_commentType success:^(CommentInfo *result) {
        //这儿做了两件事，把键盘关掉，隐藏hud
        [self.view endEditing:YES];
        
        //在这儿处理回复成功相关逻辑
        [CommentUtils replyResultHandle:_commentFrameArray replyType:REPLY_TYPE_REVIEWSID commentType:_commentType currentComtId:result.commentId userIdOther:_userIdOther userNameOther:_userNameOther replyContent:replyContent section:_replySection orderBy:ASC doSomeBefore:^{
            if(_commentFrameArray.count==0){
                [self showFooterView:YES];
            }
        } doSomeAfter:^{
            [_tableView reloadData];
        }];
        
        //处理完逻辑之后重置相关参数，重置完毕之后再将hud关掉，并弹出回复成功tip
        [self reSetReplyParams];[HUD hide:YES];[DialogUtils showTipsWithView:self.navigationController.view String:@"回复成功"];
        
    } failure:^(NSError *error) {
        [HUD hide:YES];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"回复失败"];
    }];
}

/**
 *  CELL里面的回复按钮点击
 *
 *  @param index 点击的是第index条的主评论的回复
 */
-(void)replyBtnClick:(UIButton *)btn{
    _replySection = btn.tag;
    //回复的是主评论
    _commentType = @"1";
    
    CommentViewFrame *frame = _commentFrameArray[btn.tag];
    _commentId = frame.comtInfo.commentId;
    
    [_replyView setPlaceHolder: [NSString stringWithFormat:@"回复@%@",frame.comtInfo.commentName]];
    [_replyView becomeFirstResponder];
}

/**
 *  CELL里面的私信按钮点击
 *
 *  @param btn
 */
- (void)chatBtnClick:(UIButton *)btn{
    JXLog(@"私信tag=%ld",(long)btn.tag);
}

/**
 *  CELL里面子评论被点击
 *
 *  @param section 点击的第section条主评论
 *  @param index   点击的是第index条子评论
 */
-(void)childReplyItemClick:(NSInteger)section index:(NSInteger)index{
    _replySection = section;_replyIndex = index;
    //回复的是子评论
    _commentType = @"2";
    
    CommentViewFrame *frame = _commentFrameArray[section];
    _commentId = frame.comtInfo.commentId;
    
    CommentInfo *reComt = frame.comtInfo.reComment[index];
    _userIdOther = reComt.commentUserId;
    _userNameOther = reComt.commentName;
    
    [_replyView setPlaceHolder: [NSString stringWithFormat:@"回复@%@",reComt.commentName]];
    
    [_replyView becomeFirstResponder];
}

- (void)moreBtnClick:(NSInteger)index{
    JXLog(@"moreBtnClick:%ld",(long)index);
    CommentViewFrame *frame = _commentFrameArray[index];
    
    JXComtDetailCtl *detail = [[JXComtDetailCtl alloc]initWithComtId:frame.comtInfo.commentId ReplyType:REPLY_TYPE_REVIEWSID replyId:self.reviewsId startFrom:-1 mainComtInfo:frame.comtInfo];
    [self.navigationController pushViewController:detail animated:YES];
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self reSetReplyParams];
    [self.view endEditing:YES];
}

/**
 *  重置相关回复参数
 */
- (void)reSetReplyParams{
    _commentId = nil;
    _userIdOther = nil;
    _commentType = nil;
    _userNameOther = nil;
    [_replyView setPlaceHolder:nil];
    [_replyView setText:nil];
    _replySection = _replyIndex = -1;
    _commentType = @"0";
}

-(void)showFooterView:(BOOL)flag{
    if(_commentFrameArray.count || flag){
        [_tableView beginUpdates];
        [_tableView setTableFooterView:[[UIView alloc]init]];
        [_tableView endUpdates];
    }else{
        EmptyComtView *view = [[EmptyComtView alloc]init];
        [_tableView setTableFooterView:view];
    }
}

#pragma Mark - tableview 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger count = _commentFrameArray.count;
    //判断没有数据就不显示表格线，有数据则显示
    if(count){
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else{
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentCell *cell = [CommentCell cellWithTableView:tableView];
    [cell.comtCellView setTag:indexPath.row];
    [cell.comtCellView setDelegate:self];
    [cell setComtframe:_commentFrameArray[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentViewFrame *frame = _commentFrameArray[indexPath.row];
    return frame.frame.size.height;
}

-(void)goBtnClick{
    [Utils dealUrlWithController:self url:_reviewsResult.reviews.url title:@"" fromWebView:NO];
}

-(void)share{
    // 弹出分享窗体
    sheet = [[CustomActionSheet alloc] initWithButtons:[NSArray arrayWithObjects:
                                                        [CustomActionSheetButton buttonWithImage:[UIImage imageNamed:@"btn_share_circle"] title:@"朋友圈"],
                                                        [CustomActionSheetButton buttonWithImage:
                                                         [UIImage imageNamed:@"btn_share_wx"] title:@"微信"],
                                                        nil]];
    sheet.delegate = self;
    [sheet showInView:self.view];
    //重新设置高度,并隐藏蒙层
    [_bg_btn setSize:CGSizeMake(JXScreenW, JXScreenH-sheet.height)];
    [_bg_btn setHidden:NO];
}

-(void)beforeClick{//点击蒙层
    [sheet dissmiss];
    [_bg_btn setHidden:YES];
}

-(void)choseAtIndex:(NSInteger)index{
    [_bg_btn setHidden:YES];
    //获取想要分享的参数
    NSString* share_root_url = [NSString stringWithFormat:@"%@%@",BASE_URL,POSTS_OR_REVIEWS_SHARE_URL];
    NSString* desReveiwsId = [[[DESSecurity alloc]init] TripleDES:[NSString stringWithFormat:@"%@",_reviewsId] encryptOrDecrypt:kCCEncrypt];
    desReveiwsId = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)desReveiwsId, nil, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
    NSString* share_title = [[_reviewsResult reviews] postName];
    NSString* share_url =  [NSString stringWithFormat:share_root_url,desReveiwsId,1];
    share_url = [share_url stringByReplacingOccurrencesOfString:@"api/" withString:@""];
    NSString* share_desc  =  [StringWithHtmlUtil getTextFromHtml:[[_reviewsResult reviews] content]];
    if([Utils isBlankString:_shareImgUrl]){//如果传入的图片为空,则从图文中重新取出赋值
        _shareImgUrl = [StringWithHtmlUtil getForumContextFirstImg:[[_reviewsResult reviews] content]];
    }
    _shareImg = [[UIImageView alloc]init];
    JXLog(@"url = %@ title = %@ desc = %@ img = %@  DES = %@",share_url,share_title,share_desc,_shareImg,desReveiwsId);
    switch (index) {
        case 0://朋友圈
            if(_shareImg.image){
                [Utils shareToWx:WXSceneTimeline share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
            }else{
                [_shareImg sd_setImageWithURL:[NSURL URLWithString:_shareImgUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    [self judgeShareImg:image];
                    [Utils shareToWx:WXSceneTimeline share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
                }];
            }
            break;
        case 1://微信
            if(_shareImg.image){
                [Utils shareToWx:WXSceneSession share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
            }else{
                [_shareImg sd_setImageWithURL:[NSURL URLWithString:_shareImgUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    [self judgeShareImg:image];
                    [Utils shareToWx:WXSceneSession share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
                }];
            }
            break;
            
        default:
            break;
    }
}

/**
 *  处理分享的图片
 *
 *  @param image
 */
-(void)judgeShareImg:(UIImage*)image{
    if(image){
        [_shareImg setImage:image];
    }else{
        image = [UIImage imageNamed:@"ic_launcher"];
        [_shareImg setImage:image];
    }
}

@end
